<?php

namespace App\Services;

use App\Models\Crm_Contract;
use App\Models\Crm_Order;
use App\Third\Acsign\Acsing;
use App\Traits\Verify;
use Carbon\Carbon;

class ContractService
{
    public function createContract($params)
    {
        $order = Crm_Order::find($params['orderid']);

        $params['contract_sn'] = Crm_Contract::_generateSn();
        //创建电子合同
        if($params['type'] == 1) {
            //检查是否进行企业认证  返回企业信息
            $corporateCertification = Verify::corporateCertification($params['aid']);
            if(empty($corporateCertification)){
                return ['code' => 1013,'status' => false, 'data' => []];
            }

            //检查是否有合同模板 返回合同模板信息
            $contractTemplate = Verify::contractTemplate($params['aid']);
            if(empty($contractTemplate)){
                return ['code' => 1014,'status' => false, 'data' => []];
            }

            $asignInstance = new Acsing();

            // 查询签约用户信息
            $personResult = $asignInstance->getUser(md5($params['idcard']));
            if(!$personResult['rt'] || empty($personResult['data'])){
                $personResult = $asignInstance->addPersonalUser(md5($params['idcard']), $params['realname'], $params['idcard'], 1, $params['mobile'], 0, '', 1, $params['mobile'], '', 1);
                if (!$personResult['rt']) {
                    return ['status' => false,'code' => 4008,'data' => []];
                }
            }

            //电子印章
            list($templatename, $template) = $this->getTemplateData($corporateCertification, $order, $params);
            $createContract = $asignInstance->createContract($params['contract_sn'], $templatename, '30', 1, $template, '1', '1', '','');
            if (!$createContract['rt']) {
                return ['status' => false,'code' => 4010,'data' => []];
            }

            $data = [
                [
                    'contractNo' => $params['contract_sn'],
                    'account' => md5($corporateCertification->code),
                    'signType' => 3,
                    'noticeMobile' => '',
                    'signOrder' => 1,
                    'validateType' => 1,
                    'isNotice' => 0,
                    'signStrategyList' => [
                        [
                            'attachNo' => 1,
                            'locationMode' => '3',
                            'signKey' => '乙方',
                        ],
                    ],
                ],
                [
                    'contractNo' => $params['contract_sn'],
                    'account' => md5($params['idcard']),
                    'signType' => 3,
                    'noticeMobile' => '',
                    'signOrder' => 1,
                    'isNotice' => 0,
                    'validateType' => 8,
                    'signStrategyList' => [
                        [
                            'attachNo' => 1,
                            'locationMode' => '3',
                            'signKey' => '甲方',
                        ],
                    ],
                ],

            ];
            $result = $asignInstance->addSigner($data);
//          Cms_Errmsg::create(['errMsg' =>  json_encode(['from' => 'addSigner','data'=>$result])]);
            $contract = Crm_Contract::create([
                'agencyid' => $params['aid'],
                'type' => $params['type'],
                'mid' => $params['mid'],
                'total' => $params['price'],
                'signdate' => Carbon::now()->toDateString(),
                'startdate' => Carbon::now()->toDateString(),
                'enddate' => Carbon::now()->addDay($params['days'])->toDateString(),
                'minmeets' => $params['nums'],
                'days' => $params['days'],
                'nums' => $params['nums'],
                'package_remark' => $params['package_remark'],
                'order_remark' => $params['order_remark'],
                'status' => 'wait',
                'preview_url' => $result['data']['previewUrl'],
                'legal_signurl' => $result['data']['signUser'][0]['signUrl'],
                'legal_name' => $result['data']['signUser'][0]['name'],
                'legal_status' => 1,
                'user_signurl' => $result['data']['signUser'][1]['signUrl'],
                'user_name' => $result['data']['signUser'][1]['name'],
                'user_status' => 1
            ]);
            if(!$contract){
                throw new \Exception("创建Crm_Contract电子合同失败");
            }

        }else{

        }
    }

    public function getTemplateData($corporateCertification, $order,$params){
        $startDate = Carbon::now()->toDateTimeString();
        $endDate = Carbon::now()->addDay($order->days)->toDateTimeString();

        $asignInstance = new Acsing();
        $controlList = $asignInstance->getTemplateList($params['templateident']);
        $controlData = $asignInstance->getTemplateData($params['templateident']);

        $filldata = [];
        $dataKey = ['签约门店','合同编号','甲方','甲方姓名','甲方性别','甲方身份证','甲方联系方式','乙方','乙方公司','乙方公司地址','乙方法人代表','乙方联系方式','服务期限天','服务开始日期','服务结束日期','签约日期','乙方授权代表','服务人数','签订金额','甲方签名身份证','甲方签名姓名','备注'];
        $dataVal = [$corporateCertification->name,$params['contract_sn'],$order->realname,$order->realname,$params['gender'] == '1' ? "男" : "女",$order->idcard,$order->mobile,$corporateCertification->name, $corporateCertification->name,'中铁青岛广场',$corporateCertification->contacts, $corporateCertification->mobile,$order->days,$startDate,$endDate,$startDate, $corporateCertification->contacts,$order->nums,$order->price,$order->idcard,$order->realname,$params['remark']];

        foreach ($controlData['data'] as $datum)
        {
            $key = array_search($datum['dataKey'], $dataKey);
            if ($key !== false) {
                $filldata[$datum['dataKey']] = $dataVal[$key];
            }
        }
        $template = ['templateNo' => $params['templateident'], 'fillData' => $filldata];
        $templatename = $controlList['data']['list'][0]['templateName'];
        return [$templatename, $template];
    }
}
